#pragma once

#include<iostream>
#include<pthread.h>
#include<vector>
#include<queue>
#include<string>

#define defaultNum 5

struct ThreadInfo
{
    pthread_t tid;
    std::string name;
};

template<class T>
class ThreadPool
{
public:
    // 不静态化 HandlerTask，参数列表匹配不上（隐含一个this指针） 
    static void* HandlerTask(void* arg)
    {
        ThreadPool<T>* tp = static_cast<ThreadPool<T>*>(arg);
        std::string name = tp->GetThreadName(pthread_self());
        while(true)     
        {
            tp->Lock();
            while(tp->IsEmpty()) tp->ThreadSleep();  // while 循环判断，防止误唤醒
            T t = tp->Pop();
            tp->UnLock();
            
            t();    // 处理任务
        }
    }

    void Start()
    {
        int num = _threads.size();
        for (int i = 0; i < num; ++i)
        {
            _threads[i].name = "thread[" + std::to_string(i) + "]";
            pthread_create(&_threads[i].tid, nullptr, HandlerTask, this);
        }
    }

    void Push(const T& t)
    {
        Lock();
        _task.push(t);
        Wakeup();
        UnLock();
    }

    T Pop()
    {
        T t = _task.front();
        _task.pop();
        return t;
    }

    static ThreadPool<T>* GetInstance()
    {
        // 第一层判断：当解决了并发实例对象的问题后，后续的判断总是不满足的
        // 所以如果继续加锁、解锁，串行的去做判断，效率太低
        // 因此，当实例对象后，tp = null 这个条件再也不满足，再作为外层条件来决定是否要执行加锁访问
        if(_tp == nullptr)
        {
            pthread_mutex_lock(&_lock);
            if(_tp == nullptr)      // 此处的 tp 属于临界资源，同样需要加锁保证（线程是随时可能被切换的）
            {
                std::cout << "log: singleton create done first!" << std::endl;
                _tp = new ThreadPool<T>();
            }
            pthread_mutex_unlock(&_lock);
        }
        return _tp;
    }

private:
    ThreadPool(int num = defaultNum)
        :_threads(num)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }

    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

    ThreadPool(const ThreadPool<T>&) = delete;
    const ThreadPool<T>& operator=(const ThreadPool<T>&) = delete;

    void Lock() { pthread_mutex_lock(&_mutex); }

    void UnLock() { pthread_mutex_unlock(&_mutex); }

    void Wakeup() { pthread_cond_signal(&_cond); }

    void ThreadSleep() { pthread_cond_wait(&_cond, &_mutex); }

    bool IsEmpty() { return _task.empty(); }

    std::string GetThreadName(pthread_t tid)
    {
        for(auto& t : _threads)
            if(t.tid == tid) return t.name;
        return "None";
    }

private:
    std::vector<ThreadInfo> _threads;
    std::queue<T> _task;
    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    static ThreadPool<T>* _tp;
    static pthread_mutex_t _lock;
};

template<class T>
ThreadPool<T>* ThreadPool<T>::_tp = nullptr;

template<class T>
pthread_mutex_t ThreadPool<T>::_lock = PTHREAD_MUTEX_INITIALIZER;